#include "thread_serialport.h"

ThreadSerialPort::ThreadSerialPort(serialParameter par, QObject* parent) :
    QThread(parent),
    m_com(par.name), m_state(0)
{
    m_ser = new QSerialPort();
    m_ser->setPortName(m_com);

    if(!m_ser->open(QIODevice::ReadWrite))
    {
        m_state = 0;
        return;
    }

    m_ser->setBaudRate(par.baud, QSerialPort::AllDirections);
    m_ser->setDataBits(par.datab);
    m_ser->setFlowControl(QSerialPort::NoFlowControl);
    m_ser->setParity(par.parity);
    m_ser->setStopBits(par.stopb);

    connect(m_ser, SIGNAL(readyRead()), this, SLOT(slot_readyRead()));
    m_state = 1;
}

void ThreadSerialPort::run()
{
    if(1 == m_state) {
        emit connected();
        exec();
    }
}

void ThreadSerialPort::slot_readyRead()
{
    QByteArray ba = m_ser->readAll();

    std::shared_ptr<QByteArray> pkg = std::make_shared<QByteArray>(ba);
    emit readData(pkg);
}

int ThreadSerialPort::Send(std::shared_ptr<QByteArray> sba)
{
    std::shared_ptr<QByteArray> sbatmp = sba;
    QByteArray *send = sbatmp.get();
    m_ser->write(*send);
    int len = send->length();
    return len;
}

int ThreadSerialPort::getState()
{
    return m_state;
}
